<?php
namespace Yzadmin\Controller;
use Common\Controller\AdminBaseController;
/**
 * 后台广告位控制器
 */
class AdsController extends AdminBaseController {

  /*列表操作*/
  public function index(){
    $catid=I('catid');
    if (empty($catid)){$this->error('非法操作');}
    $category = D('Adstype')->find($catid);
    $map = array('catid'=>$category['id']);
    $list = D('Ads')->where($map)->order('sort asc,id desc')->select();
    foreach ($list as $key=>$val){
        if ($val['enddate'] < time()){
          $list[$key]['status']='<font class="red">已过期</font>';
        }else{
           $list[$key]['status']='显示';
        }
    }
    $assign = array(
      'lists'=>$list,
      'category'=>$category
    );
    $this->assign($assign);
    $this->display();
  }
  /*添加操作*/
  public function add(){
    if (IS_POST){
      $data = I('post.data');
      $data['startdate'] = strtotime($data['startdate']);
      $data['enddate'] = strtotime($data['enddate']);
      $result = D('Ads')->add($data);
      if(false !== $result){
        $this->success('数据操作成功！',U('index',array('catid'=>$data['catid'])));exit;
      }else{
        $this->error('服务器正忙，请稍后再试！');
      }
    }
    $catid=I('catid');
    if (empty($catid)){$this->error('非法操作');}
    $category = D('Adstype')->find($catid);
    $info['startdate'] = time();
    $info['enddate'] = strtotime('+2 Year');
    $info['catid'] = $category['id'];
    $assign = array(
      'info'=>$info,
      'category'=>$category
    );
    $this->assign($assign);
    $this->display('edit');
  }
  /*编辑操作*/
  public function edit(){
    if (IS_POST){
      $data = I('post.data');$id = intval(I('post.id'));
      if(empty($id)){$this->error('服务器正忙，请稍后再试！');}
      $data['startdate'] = strtotime($data['startdate']);
      $data['enddate'] = strtotime($data['enddate']);
      $result = D('Ads')->where(array('id'=>$id))->save($data);
      if(false !== $result){
        $this->success('数据操作成功！',U('index',array('catid'=>$data['catid'])));exit;
      }else{
        $this->error('服务器正忙，请稍后再试！');
      }
    }
    $id=I('get.id');$catid=I('catid');
    if (empty($catid)){$this->error('非法操作');}
    $category = D('Adstype')->find($catid);
    if (empty($id)){$this->error('非法操作');}
    $info = D('Ads')->find($id);
    if (empty($info)){$this->error('非法操作');}
    $assign = array(
      'info'=>$info,
      'category'=>$category
    );
    $this->assign($assign);
    $this->display('edit');
  }

  /*删除操作*/
  function del($id = 0){
    if(IS_POST){
      if(empty($id)){echo 0;exit;}
      $result = D('Ads')->where('id='.$id)->delete();
      if($result){
        echo 1;exit;
      }else{
        echo 0;exit;
      }
    }
  }

}
